<template>
  <div class="order-management">
    <h2>我的订单</h2>

    <!-- 切换按钮 -->
    <div class="toggle-buttons">
      <el-button
          :type="orderType === 'normal' ? 'primary' : 'default'"
          @click="switchOrderType('normal')"
      >
        普通商品订单
      </el-button>
      <el-button
          :type="orderType === 'seckill' ? 'primary' : 'default'"
          @click="switchOrderType('seckill')"
      >
        秒杀商品订单
      </el-button>
    </div>

    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
      <el-form-item label="订单号">
        <el-input v-model="searchObj.id" placeholder="请输入订单号" clearable/>
      </el-form-item>
      <el-form-item :label="orderType === 'normal' ? '商品名称' : '秒杀商品名称'">
        <el-input v-model="searchObj.goods_name" :placeholder="'请输入' + (orderType === 'normal' ? '商品名称' : '秒杀商品名称')" clearable/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchObj.status" placeholder="请选择订单状态" clearable>
          <el-option label="未支付" value="0"></el-option>
          <el-option label="已支付" value="1"></el-option>
          <el-option label="已发货" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="订单ID" width="120">
        <template #default="scope">
          {{ formatOrderId(scope.row.id, scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column :prop="orderType === 'normal' ? 'goods_name' : 'seckill_goods_name'" :label="orderType === 'normal' ? '商品名称' : '秒杀商品名称'" width="200"></el-table-column>
      <el-table-column prop="goods_count" label="数量" width="80">
        <template #default="scope">
          {{ orderType === 'normal' ? scope.row.goods_count : 1 }}
        </template>
      </el-table-column>
      <el-table-column :prop="orderType === 'normal' ? 'goods_price' : 'seckill_goods_price'" :label="orderType === 'normal' ? '商品单价' : '秒杀单价'" width="100">
        <template #default="scope">
          ¥{{ orderType === 'normal' ? scope.row.goods_price : scope.row.seckill_goods_price }}
        </template>
      </el-table-column>
      <el-table-column label="总价" width="100">
        <template #default="scope">
          ¥{{ (orderType === 'normal' ? scope.row.goods_price * scope.row.goods_count : scope.row.seckill_goods_price * 1).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="scope">
          <span v-if="scope.row.status === 0">未支付</span>
          <span v-else-if="scope.row.status === 1">已支付(未发货)</span>
          <span v-else-if="scope.row.status === 2">已发货</span>
          <span v-else-if="scope.row.status === 3">已完成</span>
          <span v-else>未知状态</span>
        </template>
      </el-table-column>
      <el-table-column prop="pay_time" label="支付时间" width="180">
        <template #default="scope">
          <span v-if="scope.row.status >= 1">{{ formatDateTime(scope.row.pay_time) }}</span>
          <span v-else>---</span>
        </template>
      </el-table-column>
      <el-table-column prop="send_time" label="发货时间" width="180">
        <template #default="scope">
          <span v-if="scope.row.status >= 2">{{ formatDateTime(scope.row.send_time) }}</span>
          <span v-else>---</span>
        </template>
      </el-table-column>
      <el-table-column prop="get_time" label="收货时间" width="180">
        <template #default="scope">
          <span v-if="scope.row.status >= 3">{{ formatDateTime(scope.row.get_time) }}</span>
          <span v-else>---</span>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="订单创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
              size="small"
              type="success"
              @click="handlePay(scope.row)"
              :disabled="scope.row.status != 0"
              v-if="scope.row.status == 0"
          >
            支付
          </el-button>
          <el-button
              size="small"
              type="warning"
              @click="handleReceive(scope.row)"
              v-if="scope.row.status == 2"
          >
            收货
          </el-button>
          <el-button
              size="small"
              type="primary"
              @click="showLogistics(scope.row)"
              v-if="scope.row.status == 2 || scope.row.status == 3"
          >
            查看物流
          </el-button>
          <el-button
              size="small"
              type="info"
              disabled
              v-if="scope.row.status == 1">
            已支付
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 物流信息弹窗 -->
    <el-dialog
        v-model="logisticsDialogVisible"
        title="物流信息"
        width="90%"
        top="5vh"
        :before-close="handleLogisticsDialogClose"
    >
      <UserMap
          ref="userMap"
          v-if="logisticsDialogVisible"
          :order-info="selectedOrder"
          :ship-address="shipAddress"
          :receive-address="receiveAddress"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue'
import {ElMessage} from 'element-plus'
import orderApi from '@/api/order_api.js'
import seckillOrderApi from '@/api/seckill/seckillOrder_api.js'
import goodsApi from '@/api/goods_api.js'
import seckillGoodsApi from '@/api/seckill/seckillGoods_api.js'
import orderAddrApi from '@/api/orderAddr_api.js'
import paymentApi from '@/api/payment_api.js'
import Login_api from "@/api/login_api.js"
import UserMap from '@/view/map/UserMap.vue'

// 表格数据
const tableData = ref([])
const total = ref(0)

// 用户ID
const userId = ref(null)

// 订单类型：normal-普通订单，seckill-秒杀订单
const orderType = ref('normal')

// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  id: '',
  user_id: null, // 默认用户ID为null，实际应该从登录信息中获取
  goods_name: '',
  status: '', // 默认展示未支付订单
})

// 物流弹窗相关
const logisticsDialogVisible = ref(false)
const selectedOrder = ref(null)
const userMap = ref(null)
const shipAddress = ref('')
const receiveAddress = ref('')

// 页面加载完成后查询数据
onMounted(async () => {
  try {
    const userRes = await Login_api.logininfo()
    userId.value = userRes.id
    console.log("userId111", userId.value);
    searchObj.value.user_id = userRes.id
    await search()
  } catch (error) {
    console.error("获取用户信息失败:", error)
  }
})

// 监听订单类型变化
watch(orderType, () => {
  // 重置搜索条件并重新查询
  resetSearch()
})

// 切换订单类型
const switchOrderType = (type) => {
  orderType.value = type
}

// 查询订单列表
const search = async () => {
  try {
    // 处理查询参数
    const queryParams = { ...searchObj.value };

    // 如果输入了订单号，转换为实际ID进行精确查询
    if (queryParams.id) {
      // 从格式化ID中提取实际ID（去掉日期前缀）
      const prefix = orderType.value === 'normal' ? 'X' : 'S'
      const match = queryParams.id.match(new RegExp(`${prefix}\\d{4}(\\d{3})`));
      if (match) {
        queryParams.id = parseInt(match[1], 10);
      } else {
        // 如果格式不匹配，尝试直接使用输入值
        const numericId = parseInt(queryParams.id, 10);
        if (!isNaN(numericId)) {
          queryParams.id = numericId;
        }
      }
    }

    // 处理商品名称查询字段
    if (queryParams.goods_name) {
      if (orderType.value === 'normal') {
        // 普通订单使用 goods_name 字段
        queryParams.goods_name = queryParams.goods_name;
      } else {
        // 秒杀订单使用 seckill_goods_name 字段
        queryParams.seckill_goods_name = queryParams.goods_name;
        delete queryParams.goods_name;
      }
    }

    console.log('发送的查询参数:', queryParams)

    let result
    if (orderType.value === 'normal') {
      // 查询普通订单
      result = await orderApi.getOrderPage(searchObj.value.current, searchObj.value.limit, queryParams);
    } else {
      // 查询秒杀订单
      result = await seckillOrderApi.getSeckillOrderPage(searchObj.value.current, searchObj.value.limit, queryParams);
    }

    console.log('收到的响应数据:', result)

    // 处理订单数据，获取商品名称
    if (result.records) {
      for (let i = 0; i < result.records.length; i++) {
        const order = result.records[i];
        // 如果订单中没有商品名称但有goods_id，则获取商品名称
        if (orderType.value === 'normal') {
          if (!order.goods_name && order.goods_id) {
            try {
              const goodsResult = await goodsApi.getGoodsById(order.goods_id);
              console.log('商品信息:', goodsResult)
              if (goodsResult || goodsResult.data) {
                console.log('商品名称:', goodsResult.name)
                order.goods_name = goodsResult.name;
              }
            } catch (error) {
              console.error('获取商品信息失败:', error);
            }
          }
        } else {
          // 秒杀订单处理
          if (!order.seckill_goods_name && order.seckill_goods_id) {
            try {
              const seckillGoodsResult = await seckillGoodsApi.getSeckillGoodsById(order.seckill_goods_id);
              console.log('秒杀商品信息:', seckillGoodsResult)
              if (seckillGoodsResult && seckillGoodsResult.data) {
                // 获取对应的商品信息
                const goodsResult = await goodsApi.getGoodsById(seckillGoodsResult.data.goods_id);
                console.log('商品信息:', goodsResult)
                if (goodsResult && goodsResult.data) {
                  console.log('商品名称:', goodsResult.name)
                  order.seckill_goods_name = goodsResult.name;
                }
              } else if (seckillGoodsResult && seckillGoodsResult.goods_id) {
                // 获取对应的商品信息
                const goodsResult = await goodsApi.getGoodsById(seckillGoodsResult.goods_id);
                console.log('商品信息:', goodsResult)
                if (goodsResult && goodsResult.data) {
                  console.log('商品名称:', goodsResult.name)
                  order.seckill_goods_name = goodsResult.name;
                }
              }
            } catch (error) {
              console.error('获取秒杀商品信息失败:', error);
            }
          }
        }
      }
    }

    tableData.value = result.records
    total.value = result.total
  } catch (error) {
    console.error('查询订单列表时出错:', error)
    tableData.value = []
    total.value = 0
  }
}

// 重置查询条件
const resetSearch = () => {
  searchObj.value.id = ''
  searchObj.value.goods_name = ''
  searchObj.value.status = ''
  searchObj.value.current = 1
  search()
}

// 分页大小改变
const handleSizeChange = () => {
  search()
}

// 当前页改变
const handleCurrentChange = () => {
  search()
}

// 处理查询
const handlerSearch = () => {
  searchObj.value.current = 1
  search()
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''

  // 创建Date对象，自动处理时区
  const date = new Date(dateTimeStr)

  // 使用toLocaleString来正确显示本地时间
  // 格式化为"YYYY-MM-DD HH:mm:ss"格式
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 格式化订单ID
const formatOrderId = (id, createTime) => {
  if (!id || !createTime) return id;

  const date = new Date(createTime);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const formattedId = String(id).padStart(3, '0');

  // 根据订单类型使用不同的前缀
  const prefix = orderType.value === 'normal' ? 'X' : 'S'

  return `${prefix}${month}${day}${formattedId}`;
}

// 处理支付
const handlePay = async (row) => {
  try {
    if (orderType.value === 'normal') {
      // 调用后端支付宝支付接口，使用我们自定义的http请求方法确保携带认证信息
      const response = await fetch(`/api/order/alipay/pay?id=${row.id}`, {
        headers: {
          'Authorization': localStorage.getItem('token')
        }
      });
      if (response.ok) {
        const html = await response.text();
        // 创建一个新窗口显示支付宝支付页面
        const newWindow = window.open();
        newWindow.document.write(html);
        newWindow.document.close();

        // 轮询检查支付状态
        const checkPaymentStatus = async () => {
          const updatedOrder = await orderApi.getOrderById(row.id);
          if (updatedOrder.status === 1) {
            // 支付成功
            clearInterval(pollingInterval);
            await search();
            ElMessage.success('支付成功');
          } else if (updatedOrder.status > 1) {
            // 订单状态异常
            clearInterval(pollingInterval);
            ElMessage.warning('订单状态异常，请刷新页面查看最新状态');
          }
        };

        // 每2秒检查一次支付状态，持续3分钟
        const pollingInterval = setInterval(checkPaymentStatus, 2000);
        setTimeout(() => {
          clearInterval(pollingInterval);
        }, 180000);
      } else {
        ElMessage.error('支付请求失败: ' + response.status);
      }
    } else {
      // 秒杀订单支付逻辑
      const response = await fetch(`/api/seckill/order/alipay/pay?id=${row.id}`, {
        headers: {
          'Authorization': localStorage.getItem('token')
        }
      });
      if (response.ok) {
        const html = await response.text();
        // 创建一个新窗口显示支付宝支付页面
        const newWindow = window.open();
        newWindow.document.write(html);
        newWindow.document.close();

        // 轮询检查支付状态
        const checkPaymentStatus = async () => {
          const updatedOrder = await seckillOrderApi.getSeckillOrderById(row.id);
          if (updatedOrder.status === 1) {
            // 支付成功
            clearInterval(pollingInterval);
            await search();
            ElMessage.success('支付成功');
          } else if (updatedOrder.status > 1) {
            // 订单状态异常
            clearInterval(pollingInterval);
            ElMessage.warning('订单状态异常，请刷新页面查看最新状态');
          }
        };

        // 每2秒检查一次支付状态，持续3分钟
        const pollingInterval = setInterval(checkPaymentStatus, 2000);
        setTimeout(() => {
          clearInterval(pollingInterval);
        }, 180000);
      } else {
        ElMessage.error('支付请求失败: ' + response.status);
      }
    }
  } catch (error) {
    ElMessage.error('支付失败: ' + error.message);
  }
}

// 处理收货
const handleReceive = async (row) => {
  const now = new Date();
  console.log("现在是:", now);
  // 为了保持时区正确性，我们使用本地时间格式化
  const getTime = now.getFullYear() + '-' +
      String(now.getMonth() + 1).padStart(2, '0') + '-' +
      String(now.getDate()).padStart(2, '0') + 'T' +
      String(now.getHours()).padStart(2, '0') + ':' +
      String(now.getMinutes()).padStart(2, '0') + ':' +
      String(now.getSeconds()).padStart(2, '0');

  try {
    if (orderType.value === 'normal') {
      // 更新订单状态为已完成(3)
      const updatedOrder = {
        ...row,
        status: 3,
        get_time: getTime // 添加收货时间
      };
      await orderApi.updateOrder(updatedOrder);
    } else {
      // 更新秒杀订单状态为已完成(3)
      const updatedOrder = {
        ...row,
        status: 3,
        get_time: getTime // 添加收货时间
      };
      await seckillOrderApi.updateSeckillOrder(updatedOrder);
    }
    await search();
    ElMessage.success('收货成功');
  } catch (error) {
    ElMessage.error('收货失败: ' + error.message);
  }
}

// 显示物流信息
const showLogistics = async (row) => {
  try {
    selectedOrder.value = {...row} // 创建副本以避免响应式问题

    if (orderType.value === 'normal') {
      // 获取发货地址（来自商品的origin字段）
      const goodsResult = await goodsApi.getGoodsById(row.goods_id);

      if (goodsResult && goodsResult.origin) {
        shipAddress.value = goodsResult.origin;
        console.log("发货地址:", shipAddress.value);
      } else {
        shipAddress.value = '北京市朝阳区阜荣街10号'; // 默认发货地址
      }

      // 获取收货地址（来自订单地址）
      if (row.order_addr_id) {
        const addrResult = await orderAddrApi.getOrderAddrById(row.order_addr_id);

        console.log("收货地址:", addrResult);
        if (addrResult) {
          receiveAddress.value = addrResult.address;
        } else {
          receiveAddress.value = '北京市海淀区中关村大街1号'; // 默认收货地址
        }
      } else {
        receiveAddress.value = '北京市海淀区中关村大街1号'; // 默认收货地址
      }
    } else {
      // 秒杀订单物流信息
      // 获取发货地址（来自商品的origin字段）
      // 先获取秒杀商品信息
      const seckillGoodsResult = await seckillGoodsApi.getSeckillGoodsById(row.seckill_goods_id);
      let goodsId = null;
      if (seckillGoodsResult && seckillGoodsResult.data) {
        goodsId = seckillGoodsResult.data.goods_id;
      } else if (seckillGoodsResult && seckillGoodsResult.goods_id) {
        goodsId = seckillGoodsResult.goods_id;
      }

      if (goodsId) {
        const goodsResult = await goodsApi.getGoodsById(goodsId);

        if (goodsResult && goodsResult.origin) {
          shipAddress.value = goodsResult.origin;
          console.log("发货地址:", shipAddress.value);
        } else {
          shipAddress.value = '北京市朝阳区阜荣街10号'; // 默认发货地址
        }
      } else {
        shipAddress.value = '北京市朝阳区阜荣街10号'; // 默认发货地址
      }

      // 获取收货地址（来自订单地址）
      if (row.order_addr_id) {
        const addrResult = await orderAddrApi.getOrderAddrById(row.order_addr_id);

        console.log("收货地址:", addrResult);
        if (addrResult) {
          receiveAddress.value = addrResult.address;
        } else {
          receiveAddress.value = '北京市海淀区中关村大街1号'; // 默认收货地址
        }
      } else {
        receiveAddress.value = '北京市海淀区中关村大街1号'; // 默认收货地址
      }
    }

    logisticsDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取物流信息失败: ' + error.message);
  }
}

// 关闭物流信息弹窗
const handleLogisticsDialogClose = (done) => {
  selectedOrder.value = null
  shipAddress.value = ''
  receiveAddress.value = ''
  done()
}
</script>

<style scoped>
.order-management {
  padding: 20px;
  background-color: #fff;
}

.order-management h2 {
  margin-bottom: 20px;
}

.toggle-buttons {
  margin-bottom: 20px;
}

.toggle-buttons .el-button {
  margin-right: 10px;
}

.demo-form-inline {
  margin-bottom: 20px;
}

:deep(.el-dialog__body) {
  padding: 0;
  height: 70vh;
}
</style>
